const BaseRest = require('../rest.js');

module.exports = class extends BaseRest {
  async roleListAction() {
    const role = this.model('role');
    const roleList = await role.select();
    this.success(roleList);
  }
  async userAction() {
    const roleId = this.get('roleId')
    const user = this.model('user')
    const modelInstance = this.modelInstance
    const role = await modelInstance.where({id: roleId}).find()
    let notRoleUser
    if (role.user.length === 0) {
      notRoleUser = await user.select()
    } else {
      const roleUserIds = []
      role.user.forEach(item => {
        roleUserIds.push(item.id)
      })
      notRoleUser =  await user.where({id: ['NOTIN', roleUserIds]}).select()
    }

    this.success( {
      has: role.user,
      not: notRoleUser
    });
  }

  /**
   * 给角色添加用户
   * @returns {Promise.<void>}
   */
  async addUserAction() {
    const {roleId, userIds} = this.post()
    const addList = []
    userIds.forEach(id => {
      addList.push({role_id: roleId,user_id: id})
    })
    const insertIds = await this.model('user_role').addMany(addList)
    this.success(insertIds)
  }

  /**
   * 删除角色的用户
   * @returns {Promise.<void>}
   */
  async deleteUserAction() {
    const {roleId, userIds} = this.post()
    const rows = await this.model('user_role').where({role_id: roleId,user_id: ['IN', userIds]}).delete()
    this.success({affectedRows: rows})
  }

  /**
   * 保存角色菜单
   * @returns {Promise.<void>}
   */
  async saveMenuAction() {
    const {roleId, menuIds} = this.post()
    let role = await this.modelInstance.where({id: roleId}).find()
    role.menu_list = menuIds.join(',')
    role = await this.modelInstance.update(role)
    this.success(role)
  }

  /**
   * 删除角色菜单
   * @returns {Promise.<void>}
   */
  async deleteMenuAction() {
    const {roleId} = this.post()
    let role = await this.modelInstance.where({id: roleId}).find()
    role.menu_list = ''
    role = await this.modelInstance.update(role)
    this.success(role)
  }
};
